/*
    Project:        Home Power Control
    File:           HPCUnit.cpp
    Author:         christian@karunamusic.at
    Date:           12.2014
    Description:    A collection of sensors grouped together.
 */

#include <sstream>
#include <exception>
#include "globals.h"
#include "HPCUnit.h"

using namespace std;

HPCUnit::HPCUnit( unsigned long id,string name ) : m_ID(id), m_Name(name)
{
    PROFILE_THIS;
}

HPCUnit::~HPCUnit()
{
    PROFILE_THIS;

    for ( HPCSensor* sens: m_Sensors )
    {
        delete sens;
    }
}

string HPCUnit::asString() const
{
    stringstream s;
    s << "Unit " << m_Name << " (ID " << m_ID << ") with " << m_Sensors.size() << " sensors";
    return s.str();
}

HPCUnit::TConnection HPCUnit::OnChange( const TSignalChange::slot_type &subscriber )
{
    PROFILE_THIS;
    return m_OnChange.connect( subscriber );
}

HPCUnit::TConnection HPCUnit::OnAlarm( const TSignalAlarm::slot_type &subscriber )
{
    PROFILE_THIS;
    return m_OnAlarm.connect( subscriber );
}

HPCUnit& HPCUnit::operator += ( HPCSensor* sens )
{
    PROFILE_THIS;
    m_Sensors.push_back( sens );
    sens->OnChange( boost::bind(&HPCUnit::SensorChanged, this, _1, _2) );
    sens->OnAlarm ( boost::bind(&HPCUnit::SensorAlarmed, this, _1, _2, _3, _4) );

    return *this;
}

void HPCUnit::SensorChanged( HPCSensor* sender, const HPCSensorValue& val )
{
    PROFILE_THIS;
    LOG( trace, sender->Name() << " changed" );
    m_OnChange( this,sender,val );
}

void HPCUnit::SensorAlarmed( HPCSensor* sender, const HPCSensorValue& val, bool _max, unsigned int index )
{
    PROFILE_THIS;
    if ( _max )
    {
        LOG( trace, sender->Name() << " alarmed (above limit)" );
    }
    else
    {
        LOG( trace, sender->Name() << " alarmed (below limit)" );
    }
    m_OnAlarm( this,sender,val,_max,index );
}
